import {Navigate} from "react-router-dom";
import React, {lazy} from "react";
import BaseLayout from "@/layouts/base-layout";
import Home from "@/views/Home";
import NotFind from "@/views/NotFind";
import LazyLoadBoundary from "@/components/Error/LazyLoadBoundary.tsx";
import ViewError from "@/views/ViewError";
import Login from "@/views/Login";
import About from "@/views/About";
import {getMenus} from "@/utils/MuenUtils.tsx";
import {IMenu} from "@/api/authentication.ts";

const lazyLoadComponent = (path: string) => {
  try {
    const Element = lazy(() => import(`../views/${path}`))
    return (
      <LazyLoadBoundary>
        <Element/>
      </LazyLoadBoundary>
    )
  } catch (e) {
    return <NotFind/>;
  }
}

interface RouteItem {
  path?: string;
  element?: React.ReactElement
}

const menus = getMenus()
const generateRoutes = (menus: IMenu[]): RouteItem[] => {
  const routeItems: RouteItem[] = []

  for (const menu of menus) {
    if (menu.isFrame === '0') continue

    if (menu.children && menu.children.length > 0) {
      routeItems.push({
        path: menu.path || '',
        element: <Navigate to={menu.children[0].path || ''}/>
      })

      for (const childMenu of menu.children) {
        routeItems.push({
          path: childMenu.path || '/',
          element: lazyLoadComponent(childMenu.component || '')
        })
      }

    } else {
      routeItems.push({
        path: menu.path || '/',
        element: lazyLoadComponent(menu.component || '#')
      })
    }

  }
  return routeItems || []
}

const routes = [
  {
    path: '/',
    element: <BaseLayout/>,
    children: [
      {path: '', element: <Navigate to="/home"/>},
      {path: 'home', element: <Home/>},
      ...generateRoutes(menus)
    ]
  },
  {path: '/about', element: <About/>},
  {path: '/load-error', element: <ViewError msg="出错喽！组件加载失败，请返回首页" title="Error"/>},
  {path: '/login', element: <Login/>},
  {path: '*', element: <NotFind/>},
]

export default routes

